﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;

namespace SaturniLibrary.SMS.SMBGLOBAL
{
    public class SMBGLOBALGateway
    {
        private const string ResponseParttrn = @"status=(-?\d+)\scredits=(.*)";

        private static readonly Regex ResponseRegex = new Regex(ResponseParttrn, RegexOptions.Compiled);

        public static SMBGLOBALResponse Send(SMBGLOBALRequest smbrequest)
        {
            string requestURI = smbrequest.ToRequestUrl();

            if (string.IsNullOrWhiteSpace(requestURI))
            {
                return null;
            }

            SMBGLOBALResponse smbresponse = new SMBGLOBALResponse();
            ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };

            // Create a request for the URL. 		
            WebRequest request = WebRequest.Create(requestURI);

            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;

            // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();


            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            if (dataStream == null)
            {
                return null;
            }

            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);

            // Read the content.
            String resultMessage = reader.ReadToEnd();

            // Log the exception if error.
            if (resultMessage.Trim().ToUpper().StartsWith("ERR"))
            {
                //ExceptionHandler.HandleException(new HttpException(resultMessage));
            }

            // Cleanup the streams and the response.
            reader.Close();
            dataStream.Close();
            response.Close();

            Match match = ResponseRegex.Match(resultMessage);
            if (match.Success)
            {
                smbresponse.Status = int.Parse(match.Groups[1].Value);
                if (!string.IsNullOrWhiteSpace(match.Groups[2].Value))
                {
                    smbresponse.Credits = int.Parse(match.Groups[2].Value);
                }
            }
            return smbresponse;
        }
    }
}
